// pages/game/game_index/game_index.js
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
const bgm = wx.getBackgroundAudioManager();







Page({

  /**
   * 页面的初始数据
   */
  data: {
    state: 2, //农田状态

    czShow: true, //播种显示
    unlock: false, //解锁提示
    light: false, //光照设置
    names: false, //个人信息
    task: false, //任务菜单
    menu: false, //播种菜单
    menuTapCurrent: 0, //tab选项卡
    tap: true, //切换状态
    currentValue: 50, //进度条
    num: 1, //步进器
    minusStatus: '1',
    radio: '1', //性別
    icon: {
      normal: 'https://zebra-1258707023.cos.ap-chengdu.myqcloud.com/yndwd/game_ico3.png',
      active: 'https://zebra-1258707023.cos.ap-chengdu.myqcloud.com/yndwd/game_ico4.png',
    },
    indexData: '', //首页数据
    name: "", //姓名

    landstId: "", //土地id
    propId: '', //种子id

    showtext: true, //对话显示
    level: "", //等級
    showtiem: true, //播种显示 


    cache: "", //播种显示提示
    listDate: "", //种子列表


    guide: false, //指引1
    guidetwo: false, //指引2
    guidethree: false, //指引3
    guidefour: false, //指引4



  },
  //背景音乐
  backmusic: function () {
    player();

    function player() {
      bgm.title = "BGM "; // 必须要有一个title
      bgm.src = "https://zebra-1258707023.cos.ap-chengdu.myqcloud.com/yndwd/%E7%BA%AF%E9%9F%B3%E4%B9%90%20-%20%E5%AD%94%E9%9B%80.mp3";
      bgm.onEnded(() => {
        player(); // 音乐循环播放

      })

    }
  },
  // 跳转
  toShop() {
    wx.switchTab({
      url: '../../index/index',
    })
  },

  toStrategy() {
    wx.navigateTo({
      url: '../game_strategy/game_strategy',
    })
  },
  // 详情跳转
  toItem(e) {
    var id = e.currentTarget.dataset.landstid
    var cache = wx.getStorageSync("cache");
    console.log(cache)
    wx.navigateTo({
      url: '../game-rice-item/game-rice-item?userLandId=' + id,
    })
    wx.setStorageSync("cache", 1);

  },

  // 记录跳转
  toList() {
    wx.navigateTo({
      url: '../game-record-list/game-record-list',
    })
  },

  // 兑换跳转
  exchange() {
    wx.navigateTo({
      url: '../game-exchange-list/game-exchange-list',
    })
  },


  // 阳光进度条
  onDrag(event) {
    this.setData({
      currentValue: event.detail.value,
    });
  },


  //性别单选 
  onChange(event) {
    console.log(event)
    this.setData({
      radio: event.detail,
    });
  },


  //  延迟显示
  up() {
    console.log("执行")
    let that = this
    var showtext = true
    setInterval(function (e) {
      if (showtext == true) {
        that.setData({
          showtext: false
        })
        showtext = false
      } else {
        that.setData({
          showtext: true
        })
        showtext = true
      }
    }, 5000);

  },


  // 解锁弹框控制
  unlockShow(e) {
    console.log(e)
    this.setData({
      level: e.currentTarget.dataset.level,
      unlock: true
    });
  },

  unlockClose() {
    this.setData({
      unlock: false
    });
  },


  // 光照弹出框
  lightShow() {
    this.setData({
      light: true
    });
  },

  lightClose() {
    this.setData({
      light: false
    });
  },


  // 个人设置
  nameShow() {
    this.setData({
      names: true
    });
  },

  nameClose() {
    this.setData({
      names: false,
      name: this.data.indexData.gameNickName
    });
  },


  // 播种菜单

  menuShow() {
    this.setData({
      menu: true
    });
  },

  menuClose() {
    this.setData({
      menu: false
    });
  },

  // 任务菜单
  taskShow() {
    this.setData({
      task: true
    });
  },

  taskClose() {
    this.setData({
      task: false
    });
  },

  // 引导控制
  // 首次调用
  toNew() {
    // 首次引导
    let guide1 = wx.getStorageSync("guide1");
    console.log(guide1)
    if (guide1 == '') {
      this.guideShow()
    }
  },


  // 指引1
  guideShow() {
    this.setData({
      guide: true
    });

  },

  guideClose() {
    this.setData({
      guide: false
    });
    wx.setStorageSync("guide1", 1);
  },


  //点击生成海报
  onCreatPost(e) {
    this.getPostData()
  },

  //获取海报背景
  getPostData() {
    let that = this;
    util.request(api.CreateGamePoster).then(function (res) {
      if (res.errno == 0) {
        wx.setStorageSync("imgcode", res.data.QRcode);
        wx.setStorageSync("imgbg", 'https://zebra-1258707023.cos.ap-chengdu.myqcloud.com/yndwd/game_index_bgs.png');

        that.setData({
          isCanDraw: !that.data.isCanDraw
        })

      } else {
        util.myToast(res.errmsg)
      }
    });
  },



  // 指引2
  guidetwoShow() {
    let guide2 = wx.getStorageSync("guide2");
    if (guide2 == "") {
      this.setData({
        guidetwo: true
      });
    }
  },

  guidetwoClose() {
    this.setData({
      guidetwo: false
    });
    wx.setStorageSync("guide2", 1);
  },

  // 指引3
  guidethreeShow() {
    let guide3 = wx.getStorageSync("guide3");
    if (guide3 == '') {
      this.setData({
        guidethree: true,
      });
    }

  },

  guidethreeClose() {
    this.setData({
      guidethree: false
    });
    wx.setStorageSync("guide3", 1);
  },

  // 指引4
  guidefourShow() {
    let guide4 = wx.getStorageSync("guide4");
    if (guide4 == '') {
      this.setData({
        guidefour: true,
      });
    }

  },

  guidefourClose() {
    this.setData({
      guidefour: false
    });
    wx.setStorageSync("guide4", 1);
  },






  // 步进器

  bindMinus: function () {
    var num = this.data.num;
    // 如果大于1时，才可以减  
    if (num > 1) {
      num = num - 0.5;;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },



  /* 点击加号 */
  bindPlus: function () {
    var num = this.data.num;
    // 不作过多考虑自增1  
    num = num + 0.5;
    if (num <= 24) {
      // 只有大于一件的时候，才能normal状态，否则disable状态  
      var minusStatus = num < 1 ? 'disabled' : 'normal';
      // 将数值与状态写回  
      this.setData({
        num: num,
        minusStatus: minusStatus
      });
    }


  },



  /* 输入框事件 */
  bindManual: function (e) {
    var num = e.detail.value;
    // 将数值与状态写回  
    this.setData({
      num: num
    });
  },


  // 首页请求
  getGamedata() {
    let cache = wx.getStorageSync("cache");
    var that = this;
    util.gameRequest(api.Gameindex, {}, 'get').then(function (res) {
      if (res.errno === 0) {
        console.log(res.data.lands[1])
        that.setData({
          LandsFrist: res.data.lands[0],
          LandsTwo: res.data.lands[1],
          LandsThree: res.data.lands[2],
          LandsFour: res.data.lands[3],
          LandsFive: res.data.lands[4],
          LandsSix: res.data.lands[5],
          LandsSeven: res.data.lands[6],
          LandsEight: res.data.lands[7],
          LandsNine: res.data.lands[8],

          indexData: res.data,
          name: res.data.gameNickName,
          cache: cache
        })


      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });
  },

  // 首页刷新
  getGamedatas() {
    let cache = wx.getStorageSync("cache");
    var that = this;
    util.gameRequestNoLoading(api.Gameindex, {}, 'get').then(function (res) {

      if (res.errno === 0) {
        console.log(res.data.lands[1])
        that.setData({
          LandsFrist: res.data.lands[0],
          LandsTwo: res.data.lands[1],
          LandsThree: res.data.lands[2],
          LandsFour: res.data.lands[3],
          LandsFive: res.data.lands[4],
          LandsSix: res.data.lands[5],
          LandsSeven: res.data.lands[6],
          LandsEight: res.data.lands[7],
          LandsNine: res.data.lands[8],

          indexData: res.data,
          name: res.data.gameNickName,
          cache: cache

        })

      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });
  },

  // 修改昵称
  bindinputName(event) {
    this.name = event.detail.value;
    console.log(this.name)
    this.setData({
      name: this.name
    });
  },

  updateNickName() {
    var that = this;
    if (that.data.name == "") {
      wx.showToast({
        title: '姓名不能为空',
        icon: "none"
      })
      return;
    }
    util.gameRequestNoLoading(api.updateNickName, {
      userGameNickName: that.data.name
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        console.log(res)
        wx.showToast({
          title: '修改成功',
          icon: "none"
        })
        that.setData({
          names: false,
        })
        that.getGamedatas()


      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });
  },


  // 土地操作
  // 开垦
  landinit(e) {
    let numberId = e.currentTarget.dataset.id
    console.log(numberId)
    var that = this;
    util.gameRequest(api.Landinit, {
      userLandId: numberId
    }, 'get').then(function (res) {
      if (res.errno === 0) {
        that.getGamedatas()
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });

    // 新手指导2
    that.guidetwoShow()

  },

  // 土地播种
  landMenu(e) {
    console.log(e)
    var that = this;
    // 打开菜单
    this.menuShow()
    // 打开指引
    this.guidethreeShow()


    // 获取绑定的土地列表
    var current = e.currentTarget.dataset.current; //获取到绑定的数据
    console.log(current)
    // 默认穿第一块土地
    var landstid = e.currentTarget.dataset.landstid; //获取土地id
    this.getBozhongData(landstid, current);

  },

  // 土地列表查询
  getBozhongData(landstid, current) {
    // 发起请求
    var that = this;
    util.gameRequest(api.LandProps, {
      id: landstid
    }, 'get').then(function (res) {
      if (res.errno === 0) {
        console.log(res.data.lands[0])
        var listDate = res.data.props

        for (var x in listDate) {
          var mTime = listDate[x].needTime;
          mTime = that.formatSeconds(mTime);
          listDate[x].needTime = mTime;

        }

        that.setData({
          laFist: res.data.lands[0],
          laTwo: res.data.lands[1],
          laThree: res.data.lands[2],
          laFour: res.data.lands[3],
          laFive: res.data.lands[4],
          laSix: res.data.lands[5],
          laSeven: res.data.lands[6],
          laEight: res.data.lands[7],
          lansNine: res.data.lands[8],
          landstId: res.data.lands[0].id,
          listDate: listDate,


          landstId: landstid,
          menuTapCurrent: current,
        })
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });
  },


  // 选项卡
  menuTap: function (e) {
    // 打开切换框、
    this.menuShow()
    var current = e.currentTarget.dataset.current; //获取到绑定的数据
    console.log(current)
    var landstid = e.currentTarget.dataset.landstid; //获取土地id
    this.setData({
      landstId: landstid
    })
    var that = this
    this.getBozhongData(landstid, current);

    //改变menuTapCurrent的值为当前选中的menu所绑定的数据
    this.setData({
      menuTapCurrent: current
    });
  },

  // 获取种子ID
  plant(e) {
    //获取种子id
    let propId = e.currentTarget.dataset.propid
    this.setData({
      propId: e.currentTarget.dataset.propid
    })

    // 关闭菜单
    this.setData({
      menu: false
    });

    // 光照弹出框
    this.setData({
      light: true
    });

  },

  //获取光照id
  setLight() {
    var that = this;
    // 获取光照id
    var lightTime = that.data.num
    var lightIntensity = that.data.currentValue
    util.gameRequestNoLoading(api.setLight, {
      lightTime: lightTime,
      lightIntensity: lightIntensity
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        console.log(res)
        // 播种
        var lightId = res.data.id
        that.seed(lightId)
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });



  },

  // 重置光照
  recovery() {
    this.setData({
      currentValue: 50,
      num: 1,
    })
  },

  //播种
  seed(lightId) {
    var that = this;
    // 获取土地ID
    var langdid = that.data.landstId
    console.log(langdid)
    // 获取种子id
    var proId = that.data.propId
    console.log(proId)
    // 获取光照id
    var lightId = lightId
    console.log(lightId)

    util.gameRequest(api.Seed, {
      id: langdid,
      propId: proId,
      lightId: lightId
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        console.log(res)
        that.lightClose() //关闭阳光
        that.getGamedatas() //静默刷新页面
        that.guidefourShow() //弹出指引
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });


  },

  //收割
  landFinish(e) {
    var that = this;
    console.log(e)
    // 获取土地ID
    var userLandId = e.currentTarget.dataset.landstid
    util.gameRequest(api.LandFinish, {
      userLandId: userLandId
    }, 'get').then(function (res) {
      if (res.errno === 0) {
        console.log(res)
        wx.showToast({
          title: res.data,
          icon: 'none',
          duration: 1500
        })
        that.getGamedatas()
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });
  },


  // 任务列表
  getTaskListData() {
    let that = this;
    that.taskShow()
    util.gameRequest(api.TaskParam).then(function (res) {
      if (res.errno == 0) {
        console.log(res)
        that.setData({
          taskBean: res.data,
        })

      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //任务列表无加载框
  getTaskListNoLoadingData() {
    let that = this;
    util.gameRequestNoLoading(api.TaskParam).then(function (res) {
      if (res.errno == 0) {
        that.setData({
          taskBean: res.data
        })
        that.getDataNoLoading();
      } else {
        util.myToast(res.errmsg)
      }
    });
  },

  //  签到
  attendance() {
    var time = util.formatTime(new Date())
    util.gameRequestNoLoading(api.Attendance, {
      attendanceDate: time
    }, 'post').then(function (res) {
      if (res.errno === 0) {
        console.log(res)
        this.getTaskListNoLoadingData()
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          duration: 1500
        })
      }
    });



  },

  // 时间转换
  // fortiem(listDate) {
  //   console.log(listDate)
  //   let that = this;
  //   let lens = listDate.length; //时间数据长度
  //   console.log(lens)


  //   for (var i = 0; i < lens; i++) {
  //     var intDiff = listDate[i].needTime; //获取数据中的时间
  //     var tiem = that.formatSeconds(intDiff)
  //     console.log(tiem, "时间")
  //     that.data.listDate[i].needTime = tiem; //在数据中添加difftime参数名，把时间放进去
  //   }



  //   that.setData({
  //     listDate: that.data.listDate
  //   })


  // },

  // 时转转换
  formatSeconds(intDiff) {
    console.log(intDiff)
    var secondTime = parseInt(intDiff); // 秒
    var minuteTime = 0; // 分
    var hourTime = 0; // 小时
    if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime > 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt(minuteTime / 60);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt(minuteTime % 60);
      }
    }
    var result = "" + parseInt(secondTime) + "秒";

    if (minuteTime > 0) {
      result = "" + parseInt(minuteTime) + "分" + result;
    }
    if (hourTime > 0) {
      result = "" + parseInt(hourTime) + "小时" + result;
    }
    return result;
  },





  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    // 首次指引
    this.toNew()

    //获取通过分享进入小程序携带的参数
    var uid = options.userid;
    const scene = decodeURIComponent(options.scene)
    if (uid == undefined) {
      uid = ""
    }
    console.log("userid", uid)
    wx.setStorageSync("UserID", uid)
    if (scene != undefined && scene != "undefined") {

      var arrUserid = scene.split(":");
      //存入上级代理的UserID
      wx.setStorageSync("UserID", arrUserid[1])
      console.log("userId:" + arrUserid[1]);

    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getGamedata() //首页请求
    this.up()
    this.backmusic()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    bgm.stop();
  },

  /**
   * 生命周期函数--监听页面卸载
   */

  onUnload: function () {
    bgm.stop();
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "傣王稻勐海香米，一键领取优惠",
      path: '/pages/game/game_index/game_index?userid=' + wx.getStorageSync("userid"),
      imageUrl: 'https://zebra-1258707023.cos.ap-chengdu.myqcloud.com/yndwd/game-play-bg.jpg'
    }
  }
})